<template>
  <div id="main-container" v-loading="loading" :element-loading-text="loadingText">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="Price Calendar" name="first">
        <!-- 查询条件表单  CODE START  -->
        <el-form :inline="true" :model="querPars" class="demo-form-inline">
          <el-form-item >
            <el-input placeholder="Please Enter Room PID" v-model="querPars.physical_room_id" clearable>
              <el-button slot="append" icon="el-icon-search" @click="loadData"></el-button>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-date-picker
              v-model="querPars.currentMonth"
              type="month" max="50"
              placeholder="Please Select A Month" @change="changeMonth">
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-select v-model="querPars.room_type" placeholder="Please Select A Room Type"  @change="loadData">
              <el-option label="All Room Type" value=""></el-option>
              <el-option label="1ldk|一室一厅" value="1ldk"></el-option>
              <el-option label="2ldk|两室一厅" value="2ldk"></el-option>
              <el-option label="3ldk|三室一厅" value="3ldk"></el-option>
              <el-option label="studio|单身公寓" value="studio"></el-option>
              <el-option label="share|单间" value="share"></el-option>
              <el-option label="other｜别墅或其它" value="other"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item >
            <el-input placeholder="Please Enter City" v-model="querPars.room_area" clearable>
              <el-button slot="append" icon="el-icon-search" @click="loadData"></el-button>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="loadData">Query</el-button>
          </el-form-item>
        </el-form><!-- 查询条件表单  CODE END  -->


        <el-container>
          <el-aside width="240px">
            <div class="hourse-header-wrap">
              <table class="hourse-header-table"  cellspacing="0" cellpadding="0">
                <thead>
                <th class="cmn-first" :style="{'height':this.hourseHeaderHeight+'px'}">
                  <h4>房间/房型</h4>
                </th>
                <th>
                  <strong>基础<br/>价格</strong>
                </th>
                </thead>
              </table>
            </div>
            <div class="hourse-body-wrap" ref="hourseBodyWrap" :style="{'height':this.dataWapHeight+'px'}">
              <table class="hourse-body-table"  cellspacing="0" cellpadding="0">
                <tbody>
                <template v-for="(item,_index) in hourseDataList">
                  <tr class="hourse-group" v-bind:rowId="item.id">
                    <td class="cmn-first">
                      {{item.hourseType}}
                    </td>
                    <td>
                      <DIV style="text-align: center">
                      </DIV>
                    </td>
                  </tr>
                  <!-- 房源信息 CODE START -->
                  <tr class="data-row" v-for="(rowData,rowIndex) in item.list">
                    <td class="cmn-first">
                      <div class="hourse-info-box">
                        <span>{{rowData.name}}</span>
                        <i class="el-icon-refresh" @click="doSynchro" :indexMap="_index+';'+rowIndex" title="synchro airbnb api"></i>
                      </div>
                    </td>
                    <td class="cmn-two">
                      <DIV class="hourse-info-price">
                        <strong>{{rowData.price}}</strong><br/>
                        <label>{{rowData.currency}}</label>
                      </DIV>
                    </td>
                  </tr>
                  <!--***************************************-->
                </template>
                </tbody>
              </table>

            </div>
          </el-aside>

          <el-main>
            <div class="price-header-wrap">
              <table class="price-header-table"  cellspacing="0" cellpadding="0" :style="{'width':this.wrapWidth+'px'}">
                <tbody>
                <!-- 表头日期显示 CODE START -->
                <tr class="date-list">
                  <td v-for = "(item,index) in dateList" >
                    <div class="date-object" :class="{'date-today' :item.todayFlag=='1'}" :id="item.todayFlag=='1'?'date-today':''">
                      <strong>{{item.simpleDate}}</strong>
                      <br/>
                      <strong :class="{'date-rest-day' :item.todayFlag=='2'}">{{item.upperWeekOfDay}}</strong>
                    </div>
                  </td>
                  <!-- 表头日期显示 CODE END -->

                  <!-- 表头剩余房间数量 CODE START -->
                <tr  class="hourse-counts">
                  <td v-for = "(item,index) in dateList" >
                    <strong :id="'hourseCount_'+item.date">余0</strong>
                  </td>
                </tr>
                <!-- 表头剩余房间数量 CODE END -->
                </tbody>
              </table>
            </div>

            <div class="price-body-wrap" ref="priceBodyWrap"  :style="{'height':this.dataWapHeight+'px'}" @scroll="scrollEvent">
              <table class="price-body-table"  cellspacing="0" cellpadding="0"  :style="{'width':this.wrapWidth+'px'}">
                <tbody>
                <template v-for="(_item,_index) in hourseDataList">
                  <!-- 房间类型行数据显示 -->
                  <tr class="hourse-group">
                    <td class="cmn-first" v-for = "(item,index) in dateList" >
                      &nbsp;&nbsp;{{index+1}}
                    </td>
                  </tr>
                  <!-- 订单价格信息 CODE START -->
                  <tr class="data-row" v-for="(rowData,rowIndex) in _item.list">
                    <td :id="'td_'+rowData.id+'_'+dateObj.date" :roomid="rowData.id" :pid="rowData.pid" :indexMap="_index+';'+rowIndex"  v-for = "(dateObj,i) in dateList" @click="changePrice">
                      <DIV class="hourse-info-price" :id="'div_'+rowData.id+'_'+dateObj.date" >
                        <strong>&nbsp;</strong>
                      </DIV>
                    </td>
                  </tr>
                </template>
                </tbody>
              </table>

            </div>
          </el-main>
        </el-container>
      </el-tab-pane>

      <el-tab-pane label="Batch Price Setting" name="second">
          <BatchPriceSettingForm ref="batchPriceSettingForm"></BatchPriceSettingForm>
      </el-tab-pane>
    </el-tabs>
    <el-drawer
      :title="'Current price change Room：['+modData.hourseName+']'" size="40%"
      :visible.sync="drawer">
      <PriceSettingForm ref="priceSettingForm" :pid="selPid" :roomId="selRoomId" :listingId="selListingId"></PriceSettingForm>
    </el-drawer>

  </div>
</template>

<!--
  参考：https://blog.csdn.net/qq_39792893/article/details/90489880

-->
<script>
    import Vue from 'vue'
    //import { Button, Select } from 'element-ui';
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    import moment from 'moment'//导入文件

    import BatchPriceSettingForm from "../widgets/RoomCalendarV2/BatchPriceSettingForm";
    import PriceSettingForm from "../widgets/RoomCalendarV2/PriceSettingForm";

    import {searchModel} from "@/api/model";
    import {getRoomEvents3} from "@/api/event";
    import {getLidsByPid, getPidsByLid} from '@/api/room';
    import {submitAction} from "@/api/task";


    Vue.prototype.$moment = moment;//赋值使用
    Vue.use(ElementUI);
    export default {
      name: "PriceSettingOnCalendar",
      components: {BatchPriceSettingForm,PriceSettingForm},
      mixins: [],
      created () {
        console.log("created...");
      },
      mounted(){
        console.log("mounted...");
        this.initWoH();
        this.initDateList();
        this.loadData();
      },
      data() {
        return {
          activeName:'first',
          loading:false,
          loadingText:'data load ...',
          wrapWidth: 1740,//29天*60
          hourseHeaderHeight:80, //表头单元格默认高度
          dataWapHeight:600,//默认600
          currentTotalDays: 0, //当月总天数
          today: new Date(),  //当前日期
          dateCloseStatus:1,// 0:当前月份以前的过期全部关闭，1：当前日期根据当前日期来判定，2：当月以后的
          dateList: [], //存储本月所有日期数据
          hourseDataList : null, //房间数据
          preActiveEle: null, //记录上一次点击的单元格DIV元素
          drawer: false, //控制右边抽屉是否显示
          orderColors:[
            "#00FF99","#66FFCC","#993399","#CC6699","#CCCCFF","#CC99FF","#CCFF66","#FF6699","#FF9966",
            "#00FF99","#66FFCC","#993399","#CC6699","#CCCCFF","#CC99FF","#CCFF66","#FF6699","#FF9966",
            "#00FF99","#66FFCC","#993399","#CC6699","#CCCCFF","#CC99FF","#CCFF66","#FF6699","#FF9966"
          ],
          pickerOptions: {
            shortcuts: [{
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              }
            }],
          },
          querPars:{
            physical_room_id:'', //pid
            currentMonth:null,//当前月份
            room_area:'' //城市
          },
          selPid:null,  //当前选中的PID
          selRoomId:null, //当前选中的房源主键ID
          logicRoomList:[], //LogicRoom IDS
          selListingId: null, //当前选中的 PhysicalRoom List ID
          selPriceListDatas:[], //当前选中的房态
          selOrderDatasp:[],//当前选中的房源订单
          modData:{
            hourseName:"",
            roomType:""
          },
        }
      },
      methods: {
        /**
         *  判断传入的日期是否在起始和截止日期范围内
         * */
        eqDate(startDate, endDate, eqDate){
          let flag = false;
          if(eqDate >= startDate && eqDate < endDate){
            flag = true;
          }
          // console.log("startDate="+startDate+", endDate="+endDate+", eqDate="+eqDate+", flag="+flag);
          return flag;
        },
        /**
         *  获取截止日期和起始日期之间的天数
         * */
        getDays(startDate, endDate){
          const days = moment(endDate).diff(moment(startDate), 'days')
          //console.log(endDate+" - "+startDate+ "="+ days);
          return days;
        },
        /**
         * 计算宽高
         * */
        initWoH(){
          const todayDate = this.today;
          // const todayDate = new Date();
          const currentTotalDays =  moment(todayDate).daysInMonth(); // 获取当月天数
          this.currentTotalDays = currentTotalDays;
          this.wrapWidth = this.currentTotalDays * 60;
          const bodyHeight = document.body.clientHeight;
          this.dataWapHeight = bodyHeight - 260 - 60; // 180 是页面顶部到查询条件底部的高度 60 是底部 Copyright 的高度
          //console.log("bodyHeight="+bodyHeight+",dataWapHeight="+this.dataWapHeight);
          const _this = this;
          window.setTimeout(function(){
            const priceHeaderWrapHeight = $('.price-header-wrap').outerHeight();
            const hourseHeaderWrapHeight = $('.hourse-header-wrap').outerHeight();
            if(priceHeaderWrapHeight > hourseHeaderWrapHeight){
              _this.hourseHeaderHeight = priceHeaderWrapHeight-1;
            }
            //  console.log("2priceHeaderWrapHeight="+priceHeaderWrapHeight+", 2hourseHeaderWrapHeight="+hourseHeaderWrapHeight);
          },500);
        },
        /**
         *  初始化日期数据
         **/
        initDateList(){
          this.dateList = [];
          const todayDate = this.today;
          // const currentTotalDays =  moment(todayDate).daysInMonth(); // 获取当月天数
          // this.currentTotalDays = currentTotalDays;
          this.today = moment(todayDate).format('YYYY-MM-DD');
          const vWeekOfDay=moment(this.today).format("E");
          console.log(this.today+" , vWeekOfDay="+vWeekOfDay);

          const currMonthStr = moment(todayDate).format('YYYY-MM');
          let monthNum = moment(todayDate).format('MM');
          console.log("monthNum="+monthNum);
          for(let i=1; i <= this.currentTotalDays; i++){
            let dayStr = ""+i;
            if(i<10){
              dayStr = "0"+i;
            }
            const dateStr = currMonthStr+"-"+dayStr;
            const simpleDate = monthNum+"."+dayStr;
            const upperWeekOfDayData = this.getWeekOfDay(dateStr);
            let dateObj = {...upperWeekOfDayData};
            dateObj.date = dateStr;
            dateObj.simpleDate = simpleDate;
            dateObj.zcount = 0; //剩余房间数
            console.log(dateObj);
            this.dateList.push(dateObj);
          }
        },
        /**
         * 获取当前日期是周几
         * */
        getWeekOfDay(date){
          let upperWeekOfDay = null;
          if(this.dateCloseStatus == 1 && this.today && date == this.today){
            upperWeekOfDay = '今天';
          }else{
            let vWeekOfDay=moment(date).format("E");
            vWeekOfDay = parseInt(vWeekOfDay);

            switch (vWeekOfDay) {
              case 1 :{
                upperWeekOfDay = "一";
                break;
              } case 2 :{
                upperWeekOfDay = "二";
                break;
              } case 3 :{
                upperWeekOfDay = "三";
                break;
              } case 4 :{
                upperWeekOfDay = "四";
                break;
              }case 5 :{
                upperWeekOfDay = "五";
                break;
              }case 6 :{
                upperWeekOfDay = "六";
                break;
              }case 7 :{
                upperWeekOfDay = "日";
                break;
              }default:{
                console.error(vWeekOfDay+" 是未知的周xx!");
              }

            }
          }
          let cls = null;
          let todayFlag = 0;
          if(upperWeekOfDay == '今天'){
            cls = "date-today";
            todayFlag = 1;
          }else if(upperWeekOfDay == '六' || upperWeekOfDay == '日'){
            cls = "date-rest-day";
            todayFlag = 2;
          }
          //   console.log("todayFlag="+todayFlag+", todayFlag="+todayFlag+", upperWeekOfDay="+upperWeekOfDay);
          return {upperWeekOfDay:upperWeekOfDay,todayFlag:todayFlag, cls:cls};
        },
        /**
         *  滚动条事件
         **/
        scrollEvent () {
          const box = this.$refs.priceBodyWrap;
          //  console.log("box="+box);
          let _scrollTop = box.scrollTop;
          const _scrollHeight = box.scrollHeight;
          let _scrollLeft = box.scrollLeft;
          const _scrollWidth = box.scrollWidth;
          const priceBodyWrap = $(".price-body-wrap");
          const priceBodyHight = priceBodyWrap.height();
          const priceBodyWidth = priceBodyWrap.width();
          //console.log("_scrollTop="+_scrollTop+",_scrollHeight="+_scrollHeight+",priceBodyHight="+priceBodyHight);
          const scrollArrowHeight = 17; //滚动条底部高度
          if(_scrollTop + priceBodyHight >= (_scrollHeight+scrollArrowHeight)){ //判断是否到底部
            // console.log("到底部了");
            $('.hourse-body-wrap').css("padding-bottom",scrollArrowHeight+"px");
            $('.hourse-body-wrap').css("overflow-x","scroll");
          }
          console.log("_scrollLeft="+_scrollLeft+",_scrollWidth="+_scrollWidth+",priceBodyWidth="+priceBodyWidth);
          if(_scrollLeft + priceBodyWidth >= (_scrollWidth+scrollArrowHeight)){ //判断滚动条是否到右边
            console.log("到最右边了");
            $('.price-header-wrap').css("overflow-y","scroll");
          }

          // console.log("_scrollTop="+_scrollTop);
          $('.hourse-body-wrap').scrollTop(_scrollTop);
          $('.price-header-wrap').scrollLeft(_scrollLeft);
        },
        /**
         * 月份选择后查询
         * */
        changeMonth(value){
          console.log("changeMonth...");
          console.log(value);
          console.log("querPars.currentMonth="+this.querPars.currentMonth);
          const _month = moment(value).get('month')+1;
          const _currMonth = moment(new Date()).get('month')+1;
          if(_month > _currMonth){
            this.dateCloseStatus = 2;
            this.today = value;
          }else if(_month == _currMonth){
            this.dateCloseStatus = 1;
            this.today = moment(new Date()).format('YYYY-MM-DD');
          }else{
            this.dateCloseStatus = 0;
            this.today = value;
          }
          console.log("_month="+_month+", _currMonth="+_currMonth+", this.today="+this.today);
          //  this.today = value;
          this.initWoH();
          this.initDateList();
          this.loadOrderData();
        },
        /**
         *  加载房屋和订单数据
         * */
        loadData(){
          this.loadHourseData(() => {
            this.loadOrderData();
          });
        },
        loadHourseData(callback){
          const _this = this;
          _this.loading = true;
          const{physical_room_id,room_area,room_type} = this.querPars;
          let _pars = {};
          if(physical_room_id){
            _pars.physical_room_id = physical_room_id;
          }
          if(room_area){
            _pars.room_area = room_area;
          }
          if(room_type){
            _pars.room_type = room_type;
          }
          searchModel('PhysicalRoom', {
            // extended_filter: {},
            order_by: "-id",
            page: 1,
            page_size: 50,
            //raw_filter: {},
            search_keys: _pars
            // search_keys: {
            //     physical_room_id: "lilix9",room_area: "Hokkaido"
            // }
          }).then(res => {
            _this.loading = false;
            const list = res.data.list;
            this.groupHourseData(list);
            if(callback) callback();
          });
        },
        /**
         * 对房屋数据按房型进行分组
         */
        groupHourseData(list){
          if(!list  || list.length == 0){
            this.hourseDataList = [];
            return;
          }
          const _hourseDataList = [
            {id:'1', hourseType:'1ldk|一室一厅',name:'1ldk',list:[]},
            {id:'2', hourseType:'2ldk|两室一厅',name:'2ldk',list:[]},
            {id:'3', hourseType:'3ldk|三室一厅',name:'3ldk',list:[]},
            {id:'4', hourseType:'studio|单身公寓',name:'studio',list:[]},
            {id:'5', hourseType:'share|单间',name:'share',list:[]},
            {id:'6', hourseType:'other｜别墅或其它',name:'other',list:[]}
          ];
          for(let i=0,count=_hourseDataList.length; i<count; i++){
            const hourseData = _hourseDataList[i];
            const _name = hourseData.name;
            for(let j=0, len = list.length; j<len; j++){
              const rowData = list[j];
              const room_type = rowData.room_type;
              if(room_type != _name) continue;
              let _physical_room = rowData.physical_room_id;
              const _city = rowData.room_area;
              if(_city){
                _physical_room = _physical_room+" ["+_city+"]";
              }
              //  {id:'20',name:'funhourse00020',platform:'1',pic:'../../static/img/img2.jpg',price:'900',currency:'CNY'}
              const _data = {
                id: rowData.id,
                pid: rowData.physical_room_id,
                name: _physical_room,
                roomType: rowData.room_type,
                currency: rowData.standard_currency,
                price: rowData.standard_price,
                city: _city
              };
              hourseData.list.push(_data);
            }
          }
          this.hourseDataList = _hourseDataList.filter(item => (item.list && item.list.length > 0)); //过滤掉房型中没有房源的数据
        },
        loadOrderData(callback){
          console.log("loadOrderData  ...");
          const _this = this;
          const pidAndIdsArr = this.getPIDS();
          const idArr = pidAndIdsArr[0];
          const pidArr = pidAndIdsArr[1];
          const firstDate = this.dateList[0].date;
          const lastDate = this.dateList[this.dateList.length-1].date;
          this.loading = true;
          getRoomEvents3(pidArr, firstDate, lastDate).then(res => {
            this.loading = false;
            // _this.loading = false;
            console.log(res);
            if(!res || !res.data || (!res.data.events || res.data.events.length == 0)){
              return;
            }
            const list = res.data.events;
            this.searchCustPriceList(idArr,(priceList)=>{
              _this.pushOrderAndHoursStatus(list, priceList);
              if(callback) callback(priceList);
            });
          }).catch(err => {
            this.loading = false;
            console.error(err);
          });
        },
        searchCustPriceList(physicalRoomIdArr,cb){
          const _this = this;
          _this.loading = true;
          const firstDateObj = this.dateList[0];
          const lastDateObj = this.dateList[this.dateList.length - 1];
          const firstDate = firstDateObj.date;
          let lastDate = moment(lastDateObj.date).add(1, 'd');
          lastDate = moment(lastDate).format('YYYY-MM-DD');
          console.log("lastDate="+lastDate);
          const _pars = {};
          searchModel('PriceCalendar', {
            order_by: "-id",
            page_size: 1000,
            raw_filter: {
              physical_room__in: physicalRoomIdArr,
              date__gte: firstDate,
              date__lt: lastDate
            },
            search_keys: _pars
          }).then(res => {
            _this.loading = false;
            const list = res.data.list;
           // console.log("searchCustPriceList.list ... ");
           // console.log(list);
            if(cb) cb(list);
          }).catch(err => {
            _this.loading = false;
            console.error(err);
          });
        },
        pushOrderAndHoursStatus(dataList, priceList){
          let arr = this.hourseDataList;
          for(let i=0, count=arr.length; i<count; i++){
            const data = arr[i];
            const list = data.list;
            if(!list || list.length == 0) continue;
            list.forEach(item => {
              const _pid = item.pid;
              const _id = item.id;
              const myArr = dataList.filter(obj => {
                return obj.physical_room_id == _pid;
              });
              let _orderList = [];
              let _custPriceList = [];
              let _listing = null;
              let _priceList = [];
              if(myArr && myArr.length > 0){ //订单和房态数据
                const arr = this.pushRowDatas(myArr);
                _orderList = arr[0];
                _custPriceList = arr[1];
                _listing = arr[2];
              }
              if(priceList && priceList.length > 0){ //改价数据
                _priceList = priceList.filter(item => {
                 return _id == item.physical_room;
                });
              }
              // console.log("hourseId="+_id);
              // console.log(_priceList);
              item.listing = _listing;
              item.orderList = _orderList;
              item.custPriceList = _custPriceList;
              item.priceList = _priceList;
            });
          }
          this.renderData();
        },
        pushRowDatas(eventArr){
          let orderArr = [];
          let hourseStatusArr = [];
          let _listing = null;
          eventArr.forEach(item => {
            _listing = item.listing;
            const _orders = item.orders;
            const _roomEvents = item.room_events;
            if(_orders && _orders.length > 0){  //订单数据关联
              const _newOrderArr = _orders.map(item => {
                const _id = item.id;
                const _guestName = item.guest_name;
                const _checkin = item.checkin;
                const _checkout = item.checkout;
                const _platform = item.platform;
                const _days = this.getDays(_checkin, _checkout);
                return {id: _id, startDate: _checkin, endDate: _checkout, guestName: _guestName, platform: _platform, days: _days};
              });
              orderArr = orderArr.concat(_newOrderArr);
            }


            //房态数据关联
            if(_roomEvents && _roomEvents.length > 0){
              let index = 0;
              const _newRoomEvents = _roomEvents.map(item => {
                const _id = item.id;
                const _logicalRoomId = item.logical_room_id;
                const _title = item.title;
                const _start = item.start;
                const _end = item.end;
                const _days = this.getDays(_start, _end);
                index++;
                return {id: _id, startDate: _start, endDate: _end, title: _title, days: _days, logical_room_id: _logicalRoomId};
              });
              hourseStatusArr = hourseStatusArr.concat(_newRoomEvents);
            }

          });
          return [orderArr, hourseStatusArr, _listing];
        },
        /**
         * 获取房源名数组
         */
        getPIDS(){
          let arr = this.hourseDataList;
          let pidArr = [];
          let idArr = [];
          for(let i=0, count=arr.length; i<count; i++){
            const data = arr[i];
            const list = data.list;
            list.forEach(item => {
              const _id = item.id;
              const _pid = item.pid;
              idArr.push(_id);
              pidArr.push(_pid);
            });
          }
          return [idArr, pidArr];
        },
        /**
         *  渲染数据到页面
         * */
        renderData(){
          console.log("renderData..., today="+this.today);
          $(".close-subscribe").removeClass("close-subscribe");
          $(".has-order").remove();
          for(let i=0, count=this.dateList.length; i<count; i++){
            const dateObj = this.dateList[i];
            const date = dateObj.date;
            let zcount = 0;
            for(let j=0, len = this.hourseDataList.length; j<len; j++){ //房型组遍历
              const hourseTypeData = this.hourseDataList[j];
              // const hourseTypeId = hourseTypeData.id;
              const list = hourseTypeData.list;
              for(let k=0, length=list.length; k<length; k++){ //房屋数据遍历
                const hourseData = list[k];
                const hourseId = hourseData.id;
                const price = hourseData.price;
                const orderList = hourseData.orderList;
                const custPriceList = hourseData.custPriceList;
                const priceList = hourseData.priceList;
                let isExpired = this.renderExpireDate(hourseId, date, price,priceList);
                let isClosed = this.rednerCustPriceData(hourseId,date,custPriceList);
                this.renderOrderData(hourseData,date,orderList);
                const tdId = "td_"+hourseId+"_"+date;
                const hasOrder = $("#"+tdId).attr("hasOrder");
                if(!hasOrder && !isExpired && !isClosed){
                  zcount++;
                }
              }
              // console.log(date+" = "+ zcount);
            }
            $("#hourseCount_"+date).text("余"+zcount);
          }
        },

        /**
         * 渲染当前日期之前的数据为关闭过期
         * */
        renderExpireDate(hourseId,date,price, priceList){
          const tdId = "#td_"+hourseId+"_"+date;
          const divId = "#div_"+hourseId+"_"+date;
          if(null != priceList && priceList.length > 0){
             for(let i=0, count=priceList.length; i<count; i++){
               const _item = priceList[i];
               const _date = _item.date;
               const _price = _item.price;
               if(date == _date){
                 price = _price;
                 break;
               }
             }
          }
          if(!price) price = "NoPrice";
         $(divId).html(this.getPriceHtml(price));
          if(this.dateCloseStatus >= 1 && !moment(date).isBefore(this.today)) return false;
          // console.log("today="+this.today+", date = "+date+", "+tdId+"=close-subscribe");
          $(tdId).addClass("close-subscribe");
          return true;
        },
        renderOrderData(hourseData,date,orderList){
          const hourseId = hourseData.id;
          if(!orderList || orderList.length == 0){
            return;
          }else{
            let indexColor = 0;
            for(let i=0,count=orderList.length; i<count; i++){
              const orderData = orderList[i];
              let startDate = orderData.startDate;
              let endDate = orderData.endDate;
              const flag = this.eqDate(startDate, endDate, date);
              if(!flag){
                continue;
              }else{
                const firstDate = this.dateList[0].date;
                const lastDate = this.dateList[this.dateList.length-1].date;
                if(startDate < firstDate) startDate = firstDate;
                if(endDate > lastDate) endDate = lastDate;
                const tdId = "#td_"+hourseId+"_"+date;
                const divId = "#div_"+hourseId+"_"+date;
                $(tdId).addClass("close-subscribe");
                $(tdId).attr("hasOrder","1");
                let html = "&nbsp;";
                if(date == startDate){ //显示订单进度条
                  const id = orderData.id;
                  const guestName = orderData.guestName;
                  const platform = orderData.platform || '未知';
                  const days = this.getDays(startDate, endDate)+1;
                  const width = 60 * days-30;
                  const color = this.getColor(i);
                  html = '<span class="has-order-dates" style="width:'+width+'px;background-color:'+color+'; " orderid="'+id+'"></span>';
                }
                $(divId).html(html);
              }
            }
          }
        },
        getColor(indexColor){
          return this.orderColors[indexColor];
        },
        rednerCustPriceData(hourseId,date,custPriceList){
          const tdId = "#td_"+hourseId+"_"+date;
          for(let i=0,count=custPriceList.length; i<count; i++) {
            const custPriceData = custPriceList[i];
            let startDate = custPriceData.startDate;
            let endDate = custPriceData.endDate;
            let custPriceId = custPriceData.id;
            const price = custPriceData.price;
            const flag = this.eqDate(startDate, endDate, date);
            //  console.log("startDate="+startDate+", endDate="+endDate+", date="+date+", f;lag = "+flag);
            if (!flag){
              continue;
            }

           // const divId = "#div_"+hourseId+"_"+date;
          //  const divEle = $(divId);
           // divEle.attr("data-id", custPriceId);
           // divEle.html(this.getPriceHtml(price));
            $(tdId).addClass("close-subscribe");
          }
          return $(tdId).hasClass("close-subscribe");
        },
        getPriceHtml(price){
          return '<strong style="color:#ff6633;">'+price+'</strong>';
        },
        getDatasByHourseId(hourseId, orderDatas){
          let dataList = [];
          for(let i=0, count=orderDatas.length; i<count; i++){
            const orderData = orderDatas[i];
            const _hourseId = orderData.hourseId;
            if(hourseId != _hourseId) continue;
            dataList.push(orderData);
          }
          return dataList;
        },
        handleClick(tab, event) {
          console.log(tab, event);
          console.log("index = "+ tab.index);
          const index = tab.index;
          if(index != 1) return;
          const cmpt_batchPriceSettingForm = this.$refs['batchPriceSettingForm'];
          if(cmpt_batchPriceSettingForm && cmpt_batchPriceSettingForm.refresh) { //刷新批量改价表单
            cmpt_batchPriceSettingForm.refresh(this);
          }
        },
        closeDrawer(){
          this.drawer = false;
        },
        /**
         * 改价
         */
        changePrice(event){
          const _this = this;
          let ele = event.target;
          let tagName = ele.tagName;

          // console.log("tagName="+tagName);
          while(tagName != 'TD'){
            ele = ele.parentNode;
            tagName = ele.tagName;
            if(tagName == 'TD') break;
          }

          if(this.preActiveEle){
            $(this.preActiveEle).removeClass('current-active');
          }
          const eleId = ele.id;
          //  console.log("eleId="+eleId);
          if(!eleId) return;
          // if($(ele).hasClass("close-subscribe")){
          //   return;
          // }
          this.preActiveEle = ele;
          $(ele).addClass('current-active');
          const roomId = ele.getAttribute('roomid');
          const pid = ele.getAttribute('pid');
          const indexMap = ele.getAttribute('indexMap');
          const hasorder = ele.getAttribute('hasorder');
          // console.log("changePrice...,pid="+pid+", indexMap="+indexMap+", hasorder="+hasorder);
          this.drawer = true;
          this.selPid = pid;
          this.selRoomId = roomId;
          let hourseData = null;
          if(indexMap){
            const indexArr = indexMap.split(";");
            const index = indexArr[0];
            const subIndex = indexArr[1];
            hourseData = this.hourseDataList[index].list[subIndex];
          }
          if(hourseData){
            this.modData.hourseName = hourseData.pid;
            this.modData.roomType = hourseData.roomType;
          }
         // this.loadLogicRoomIds();
          window.setTimeout(() => { //改价表单显示
            _this.showPriceSettingForm(hourseData);
          },100);
        },
        loadLogicRoomIds(){
          getLidsByPid({physical_room_id: this.selPid}).then(res => {
            console.log("loadLogicRoomIds...");
            console.log(res);
            let data = res.data
            if(!data || data.length == 0){
              return;
            }
            this.logicRoomList = data.map(item => {
              const _lid = item.lid;
              const _platform = item.platform;
              const _label = _lid+'('+_platform+')';
              return {label:_label, value: _lid};
            });

            const cmpt_priceSettingForm = this.$refs['priceSettingForm'];
            if(cmpt_priceSettingForm && cmpt_priceSettingForm.setLogicRoomList){ //改价表单 加载LogicRoomList 下拉框
              cmpt_priceSettingForm.setLogicRoomList(this.logicRoomList);
            }
          })
        },

        /**
         * 改价表单显示
         */
        showPriceSettingForm(hourseData){
          const cmpt_priceSettingForm = this.$refs['priceSettingForm'];
          if(cmpt_priceSettingForm && cmpt_priceSettingForm.refresh){ //刷新房态表单
            if(hourseData){
              this.selListingId = hourseData.listing;
              this.selPriceListDatas = hourseData.priceList;
            }else{
              this.selListingId = null;
              this.selPriceListDatas = [];
            }
            console.log("this.selPriceListDatas...");
            console.log(this.selPriceListDatas);
            cmpt_priceSettingForm.refresh(this);
          }
        },
        /**
         * ActionTask ABNB API 同步
         */
        doSynchro(event){
            const _this = this;
            let ele = event.target;
            let tagName = ele.tagName;

            console.log("tagName="+tagName);
            const indexMap = ele.getAttribute('indexMap');
            let hourseData = null;
            if(indexMap){
                const indexArr = indexMap.split(";");
                const index = indexArr[0];
                const subIndex = indexArr[1];
                hourseData = this.hourseDataList[index].list[subIndex];
            }
            if(hourseData){
                this.selListingId = hourseData.listing;
                console.log(hourseData);
                console.log("selListingId="+this.selListingId);
            }


            if(!this.selListingId){
                _this.$message.error('PhysicalRoomListing id is null,Please Check Data...!');
                return;
            }
            const actionName = "sync_price_to_airbnb";
            this.loadingText = "Calling API: "+actionName+" ...";
            this.loading = true;

            submitAction("PhysicalRoomListing", this.selListingId,actionName).then(res => {
                this.loading = false;
                _this.$notify({
                    title: 'Success',
                    message: 'ListingId:'+ this.selListingId+' call API:'+actionName+' succeeded !',
                    type: 'success'
                });

            }).catch(reason => {
                _this.loading = false;
                console.log("deleteModel Failure...");
                console.error(reason);
                _this.$notify.error({
                    title: 'Error',
                    message: 'API:'+actionName+'  call error !'
                });
                //_this.$message.error('Please Check Input Form Data Has Errors!');
            });

        }

      }

    }

</script>


<style lang="less" scoped>

  body{
    overflow: hidden;
  }
  #main-container {
    padding: 1rem;
    border: 1px solid #ebeef5;
    background-color: white;
  }


  .el-aside {
    background-color: #D3DCE6;
    color: #333;
    text-align: center;
    width: 240px;
    margin: 0px;
    padding: 0px;
    overflow: hidden;
  }

  .el-main {
    background-color: #E9EEF3;
    color: #333;
    text-align: center;
    padding: 0px;
    overflow: hidden;
  }

  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }

  .el-date-editor .el-range-separator {
    padding: 0 5px;
    line-height: 32px;
    width: 10%;
    color: #303133;
  }

  /**------ 房屋表头DIV容器 -----**/
  .hourse-header-wrap{
      overflow: hidden;
  }

  /**------ 房屋表体数据DIV容器 -----**/
  .hourse-body-wrap{
    height: 600px;
    //width: 240px;
    //background-color: #00aeef;
   // border: 1px solid red;
    overflow: hidden;
  }


  /**------ 价格表头DIV容器 -----**/
  .price-header-wrap{
    /*border: 1px solid #0000ff;*/
    overflow-x: hidden;
  }

  /**------ 价格表体数据DIV容器 -----**/
  .price-body-wrap{
    height: 600px;
    overflow: auto;
  }

  table {
    table-layout: fixed;
    background-color: white;
    border-collapse:collapse;
    border-spacing:0;
    border-left:1px solid #B7CFFF;
    border-top:1px solid #B7CFFF;
  }


  table th, td{
    border-right:1px solid #B7CFFF;
    border-bottom:1px solid #B7CFFF;
  }

  .hourse-header-table, .hourse-body-table{
    width: 240px;
  }


  .hourse-header-table th{
    font-weight:bold;
    text-align: center;
    height: 80px;

  }

  .hourse-header-table th h4{
    font-weight: bold;
  }
  .hourse-header-table th strong{
    color: #A4A7AB;
  }

  .cmn-first{
    width: 170px;
  }

  .cmn-two{
    height: 56px;
  }



  .hourse-body-table tbody tr{
    height: 40px;
  }

  .hourse-body-table tbody tr td{
    padding:5px 5px;
  }

  .hourse-group{
    background-color: #E9F2FD;
    height: 40px;
  }

  .data-row{
    height: 56px;
  }

  .hourse-info-box{
    width: 100%;
    line-height: 40px;
    position: relative;
  }

  .hourse-info-box i{
    position: absolute;
    top:-5px;
    right: 0px;
  }

  .hourse-info-box i:hover{
    color: red;
    cursor:pointer;
  }

  .hourse-body-table .img-hourse-small{
    width: 35px; height: 35px; border: none;
  }
  .hourse-body-table .img-platform-logo{
    width: 18px; height: 18px;
    margin-top: 10px;
    border-radius:50px;
    border: none;
    float: right;
  }

  .hourse-info-price{
    text-align: center;
    cursor: pointer;
  }

  .hourse-info-price strong{
    color:#ff6633;
  }

  .hourse-info-price label{
    font-weight: bold;
  }


  .hourse-info-price .has-order-dates{
    height:15px;line-height: 15px;display: inline-block;margin-top: 4px; background: #2cc642;border-radius: 10px;
  }

  .close-subscribe{
    background: url("../../static/img/close-subscribe.png") no-repeat;
  }

  .current-active{
    height: 50px; line-height: 50px;
    border: 2px solid #00aeef;
    cursor: pointer;
  }


  .price-header-table, .price-body-table{
     /* width: 1860px;*/
  }


  .price-header-table tr td{
    margin: 0px;
    padding: 0px;
  }
  .price-header-table .date-list{
    height:45px;
  }

  .date-list td{
    height: 45px;
    width: 60px;
    color:  #ACACAC;
  }

  .date-object{

  }

  .date-today{
    color:#3C89F0;
    border-radius:50px;
    background-color: #E9F2FC;
  }
  .date-rest-day{
    color:#FE595F;
  }

  .price-body-table tbody tr td{
    margin: 0px;
    width: 60px;
  }


  .date-list div{
    margin: 0px;
    padding: 0px;
  }

  .price-header-table .hourse-counts{
    height:35px;
  }

</style>
